import type { FormInstance } from 'element-plus'
import type {
  operationStatusEnum,
  lampPostTypeEnum
  // suborinateLampPostEnum // 灯杆暂去掉"规格型号"
} from '~/store/assetManagement/facilityManagement/typings'
import type { AssetLampPostDataItemType } from '../../facilityManagement/assetLampPost/typings'
import type {
  AssetLampPostBasicInformationState,
  LampPostSelectEnum,
  accomplishEnum
} from './typings'
import { defineComponent, reactive, ref, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import {
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  // ElSwitch,
  ElRadioGroup,
  ElRadioButton,
  ElLink,
  ElIcon,
  ElInputNumber,
  ElSpace
} from 'element-plus'
import { Plus, WarningFilled } from '@element-plus/icons-vue'
import { GUTTER, SPAN_STYLE_LG_ONE_SM_DOUBLE } from '~/utils/const'
import { handleTrim } from '~/utils/util'
import InputTextarea from '~/components/ProForm/InputTextarea'
import BaseUpload from '~/components/ProForm/BaseUpload'
import useVuexGetters from '~/hooks/useVuexGetters'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'AssetLampPostBasicInformation',
  props: ['detail', 'type'],
  setup: (props: { detail: AssetLampPostDataItemType; type: string }, { expose }) => {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const assetLampPostBasicInformationState = reactive<AssetLampPostBasicInformationState>({
      deliverDateDisabled: false, // "投运日期"默认可选
      isDeliverDisabled: false, // "投运状态->"默认可选
      distributionSelectBoxList: []
    })
    const optionsValidateForm = reactive<AssetLampPostDataItemType>(
      Object.assign(
        {
          isDeliver: true, // 投运状态(开关)
          // isDeliver: 1, // 投运状态(单选)
          imageUrl: []
        },
        props?.detail?.id // 初始化数据
          ? {
              id: props.detail.id,
              name: props.detail.name, // 设备名称
              categoryId: props.detail.categoryId, // 灯杆类型
              manufacturer: props.detail.manufacturer, // 生产厂家
              code: props.detail.code, // 现场杆号
              deliverDate: props.detail.deliverDate, // 投运日期
              // modelId: props.detail.modelId, // 规格型号
              validity: props.detail.validity, // 使用年限
              // isDeliver: !!(props.detail?.isDeliver ?? 1), // 投运状态(开关)
              isDeliver: props.detail?.isDeliver, // 投运状态(单选)
              postHeight: props.detail.postHeight, // 高度
              lampRamLength: props.detail.lampRamLength, // 臂长
              supply: props.detail.supply, // 供货公司
              thickness: props.detail.thickness, // 灯杆壁厚
              lampNum: props.detail.lampNum, // 灯具数量
              distributionId: props.detail.distributionId, // 所属配电设施
              distributionLoopId: props.detail.distributionLoopId, // 灯杆关联回路
              workAreaName: props.detail.workAreaName, // 所属区域/区域
              streetId: props.detail.streetId, // 所属街道id
              streetName: props.detail.streetName, // 所属街道
              memo: props.detail.memo, // 备注
              imageArr: props.detail?.imageUrl,
              imageUrl: props.detail?.imageUrl
                ? (props.detail?.imageUrl as string)?.split?.(',')
                : [],
              postHeightType: props.detail?.postHeightType
                ? Number(props.detail?.postHeightType)
                : '',
              distributionLoopArrayId: props.detail?.distributionLoopId
                ? (props.detail?.distributionLoopId as string)?.split?.(',')
                : []
            }
          : { isDeliver: 1 }
      )
    )

    const assetLampPostState = useVuexGetters('assetLampPost', ['lampPostTypeSelectList']) // 灯杆类型, ('deviceModelBylampPostTypeSelectList':灯杆暂去掉"规格型号")
    const assetWorkAreaState = useVuexGetters('assetWorkArea', [
      'workAreaSelectList',
      'postHeightTypeOpt'
    ]) // 所属区域/区域
    const streetManagementState = useVuexGetters('streetManagement', ['streetSelectList']) // 所属街道
    const powerDistributionFacilitiesState = useVuexGetters('powerDistributionFacilities', [
      'operationStatusSelectList'
    ])

    watch(
      () => optionsValidateForm.distributionId,
      () => {
        // 所属配电设施的值一变, 去搜对应的工区
        assetLampPostBasicInformationState.distributionSelectBoxList?.forEach((item) => {
          if (item.id === optionsValidateForm.distributionId) {
            optionsValidateForm.workAreaName = item.workAreaName // 所属区域/区域
            optionsValidateForm.streetId = item.streetId // 所属街道id
            const workAreaId = item.workAreaId

            // 获取所属区域/区域下拉列表
            store.dispatch('assetWorkArea/GetWorkAreaSelectListByUser')
            // 获取所属街道下拉列表
            store.dispatch('streetManagement/GetStreetSelectListByUser', { workAreaId })
          }
        })
      }
    )

    // 灯杆类型一变, 去搜对应规格型号 // 灯杆暂去掉"规格型号"
    // watch(
    //   () => optionsValidateForm.categoryId,
    //   () => {
    //     const categoryId = optionsValidateForm.categoryId
    //     store.dispatch('assetLampPost/GetDeviceModelByLampPostType', { categoryId })
    //   }
    // )

    onMounted(() => {
      editInfo() // 编辑时原内容
      getDistributionSelectBoxList() // 所属配电设施
    })

    // 编辑时原内容
    const editInfo = () => {
      // 查询回路下拉列表
      if (optionsValidateForm.distributionId)
        getLoopSelectListByDistributionId(optionsValidateForm.distributionId)
      store.dispatch('assetLampPost/GetNodeByParentCode') // 灯杆类型 下拉列表
      store.dispatch('assetWorkArea/GetWorkAreaSelectListByUser') // 获取所属区域 下拉列表
      const workAreaId = optionsValidateForm.workAreaId
      store.dispatch('streetManagement/GetStreetSelectListByUser', { workAreaId }) // 获取所属街道 下拉列表

      // 编辑时, 若投运状态已为开启, 则不能再更改
      if (optionsValidateForm.isDeliver === true && props.type === 'update') {
        assetLampPostBasicInformationState.isDeliverDisabled = true
      }

      // 投运日期是否可填
      isDeliverChange()
    }

    // 获取所属配电设施下拉列表
    const getDistributionSelectBoxList = async () => {
      const res = await store.dispatch('powerDistributionFacilities/GetDistributionSelectBoxList')
      if (res?.code === 200) {
        assetLampPostBasicInformationState.distributionSelectBoxList = res.data
      }
    }

    // 切换所属配电设施
    const handleChangeDistributionId = (val: string) => {
      optionsValidateForm.distributionLoopId = undefined
      if (val) {
        getLoopSelectListByDistributionId(val)
      } else {
        assetLampPostBasicInformationState.loopsSelectList = []
      }
    }

    // 根据配电设施id获取所属回路下拉列表
    const getLoopSelectListByDistributionId = async (distributionId: string) => {
      const res = await store.dispatch('loopMonitoringBox/GetPowerDistributionFacilityCircuit', {
        distributionId
      })
      assetLampPostBasicInformationState.loopsSelectList = res?.data || []
    }

    // 上传成功回调
    const handleUploadSuccess = (result: Record<string, any>) => {
      const link = result?.data?.link
      if (link) {
        (optionsValidateForm.imageUrl as string[])?.push(link)
      }
    }

    // 移除对应的文件
    const handleRemoveUploadFile = (file: Record<string, any>) => {
      const link = file?.url
      if (link) {
        optionsValidateForm.imageUrl = (optionsValidateForm.imageUrl as string[])?.filter(
          (item) => item !== link
        )
      }
    }

    // 输入限制
    // const onInputPower = () => {
    //   // 使用年限
    //   if (parseInt(optionsValidateForm.validity!) < 0) {
    //     optionsValidateForm.validity = ''
    //   }
    //   if (optionsValidateForm.validity !== '') {
    //     optionsValidateForm.validity = `'${optionsValidateForm.validity}'`
    //     optionsValidateForm.validity = optionsValidateForm.validity?.replace(/[^\d]/g, '')
    //   }

    //   // 灯具数量
    //   if (parseInt(optionsValidateForm.lampNum!) < 0) {
    //     optionsValidateForm.lampNum = ''
    //   }
    //   if (optionsValidateForm.lampNum !== '') {
    //     optionsValidateForm.lampNum = `'${optionsValidateForm.lampNum}'`
    //     optionsValidateForm.lampNum = optionsValidateForm.lampNum?.replace(/[^\d]/g, '')
    //   }
    // }

    // 去前后空格
    const handleInputChange = () => {
      optionsValidateForm.name = optionsValidateForm.name && handleTrim(optionsValidateForm.name) // 设备名称
      optionsValidateForm.code = optionsValidateForm.code && handleTrim(optionsValidateForm.code) // 现场杆号
      optionsValidateForm.manufacturer =
        optionsValidateForm.manufacturer && handleTrim(optionsValidateForm.manufacturer) // 生产厂家
      // optionsValidateForm.modelId =
      //   optionsValidateForm.modelId && handleTrim(optionsValidateForm.modelId) // 规格型号 // 灯杆暂去掉"规格型号"
      optionsValidateForm.supply =
        optionsValidateForm.supply && handleTrim(optionsValidateForm.supply) // 供货公司
      optionsValidateForm.memo = optionsValidateForm.memo && handleTrim(optionsValidateForm.memo) // 备注
    }

    // 投运状态 为'启用'时 才能填 投运日期
    const isDeliverChange = () => {
      if (optionsValidateForm.isDeliver) {
        assetLampPostBasicInformationState.deliverDateDisabled = false
      } else {
        optionsValidateForm.deliverDate = '' // 清空刚填的投运日期
        assetLampPostBasicInformationState.deliverDateDisabled = true
      }
    }

    //  所属街道值变化
    const streetChange = (value: string) => {
      if (!value) {
        optionsValidateForm.streetName = ''
      }
    }

    expose({ ruleFormRef, formValues: optionsValidateForm })

    return () => {
      return (
        <ElForm
          ref={ruleFormRef}
          model={optionsValidateForm}
          labelWidth="120px"
          labelPosition="right"
          class={styles['basicInformation-form']}
        >
          <ElRow gutter={GUTTER}>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="name"
                label="设备名称"
                rules={[
                  {
                    required: true,
                    whitespace: true,
                    message: '请输入设备名称',
                    trigger: 'change'
                  },
                  {
                    min: 3,
                    whitespace: true,
                    message: '请输入3～20字符长度的设备名称',
                    trigger: 'change'
                  }
                ]}
              >
                <ElInput
                  v-model={optionsValidateForm.name}
                  {...{ minlength: 3, maxlength: 20 }}
                  clearable
                  placeholder="请输入"
                  onChange={handleInputChange}
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="categoryId"
                label="灯杆类型"
                rules={[{ required: true, message: '请选择灯杆类型', trigger: 'change' }]}
              >
                <ElSelect v-model={optionsValidateForm.categoryId} clearable placeholder="请选择">
                  {assetLampPostState.lampPostTypeSelectList?.value?.map(
                    (item: lampPostTypeEnum) => (
                      <ElOption key={item?.id} label={item?.dictValue} value={item?.id!} />
                    )
                  )}
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="isDeliver"
                label="投运状态"
                rules={[{ required: true, message: '请选择投运状态', trigger: 'change' }]}
              >
                {/* 开关 */}
                {/* <ElSwitch
                  v-model={optionsValidateForm.isDeliver}
                  disabled={assetLampPostBasicInformationState.isDeliverDisabled}
                  onChange={isDeliverChange}
                /> */}
                {/* 单选 */}
                <ElRadioGroup
                  class={styles['info-form-item-full-width']}
                  v-model={optionsValidateForm.isDeliver}
                  // disabled={assetLampPostBasicInformationState.isDeliverDisabled}
                  disabled={props.type === 'update' && !!props.detail?.isDeliver}
                  onChange={isDeliverChange}
                >
                  {powerDistributionFacilitiesState.operationStatusSelectList.value?.map(
                    (item: operationStatusEnum) => (
                      <ElRadioButton label={item.dictKey}>{item.dictValue}</ElRadioButton>
                    )
                  )}
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="deliverDate"
                label="投运日期"
                rules={[
                  {
                    required: !assetLampPostBasicInformationState.deliverDateDisabled,
                    message: '投运状态开时, 投运日期必填',
                    trigger: 'change'
                  }
                ]}
              >
                <ElDatePicker
                  class={styles['info-form-item-full-width']}
                  v-model={optionsValidateForm.deliverDate}
                  valueFormat="YYYY-MM-DD"
                  disabled={assetLampPostBasicInformationState.deliverDateDisabled}
                  clearable
                  placeholder="请选择"
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="distributionId"
                label="所属配电设施"
                rules={[{ required: true, message: '请输入或选择所属配电设施', trigger: 'change' }]}
              >
                <ElSelect
                  v-model={optionsValidateForm.distributionId}
                  filterable
                  clearable
                  placeholder="请输入或选择"
                  onChange={handleChangeDistributionId}
                >
                  {assetLampPostBasicInformationState.distributionSelectBoxList?.map((item) => (
                    <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                  )) || []}
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="distributionLoopArrayId"
                label="所属回路"
                rules={[{ required: false, message: '请输入或选择所属回路', trigger: 'change' }]}
              >
                <ElSelect
                  v-model={optionsValidateForm.distributionLoopArrayId}
                  filterable
                  multiple
                  clearable
                  disabled={true}
                  placeholder="请输入或选择"
                >
                  {assetLampPostBasicInformationState.loopsSelectList?.map((item) => (
                    <ElOption key={item?.id} label={item?.loopName} value={item?.id!} />
                  )) || []}
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="manufacturer"
                label="生产厂家"
                rules={[
                  {
                    min: 3,
                    whitespace: true,
                    message: '生产厂家，若输入则应为3～20个字符',
                    trigger: 'change'
                  }
                ]}
              >
                <ElInput
                  v-model={optionsValidateForm.manufacturer}
                  {...{ minlength: 3, maxlength: 20 }}
                  clearable
                  placeholder="请输入"
                  onChange={handleInputChange}
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="code"
                label="现场杆号"
                rules={[
                  {
                    min: 3,
                    whitespace: true,
                    message: '现场杆号，若输入则应为3～20个字符',
                    trigger: 'change'
                  }
                ]}
              >
                <ElInput
                  clearable
                  v-model={optionsValidateForm.code}
                  {...{ minlength: 3, maxlength: 20 }}
                  placeholder="请输入"
                  onChange={handleInputChange}
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem prop="validity" label="使用年限">
                <ElSpace class={styles['info-form-item-full-space']} size={0}>
                  <ElInputNumber
                    // clearable
                    // {...{ maxlength: 3 }}
                    v-model={optionsValidateForm.validity}
                    precision={0}
                    min={0}
                    max={999}
                    controls={false}
                    // onInput={onInputPower}
                    placeholder="请输入"
                  />
                  <span class={styles['basicInformation-unit']}>年</span>
                </ElSpace>
              </ElFormItem>
            </ElCol>
            {/* 灯杆暂去掉"规格型号" */}
            {/* <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem prop="modelId" label="规格型号">
                <ElSelect v-model={optionsValidateForm.modelId} clearable placeholder="请选择">
                  {assetLampPostState.deviceModelBylampPostTypeSelectList?.value?.map(
                    (item: suborinateLampPostEnum) => (
                      <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                    )
                  )}
                </ElSelect>
              </ElFormItem>
            </ElCol> */}
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem prop="lampNum" label="灯具数量">
                <ElSpace class={styles['info-form-item-full-space']} size={0}>
                  <ElInputNumber
                    v-model={optionsValidateForm.lampNum}
                    precision={0}
                    min={0}
                    max={99}
                    controls={false}
                    // {...{ maxlength: 2 }}
                    // onInput={onInputPower}
                    // clearable
                    placeholder="请输入"
                  />
                  <span class={styles['basicInformation-unit']}>个</span>
                </ElSpace>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem prop="postHeight" label="高度">
                <ElSpace class={styles['info-form-item-full-space']} size={0}>
                  <ElInputNumber
                    v-model={optionsValidateForm.postHeight}
                    precision={1}
                    step={0.1}
                    min={0}
                    max={1000}
                    controls={false}
                    placeholder="请输入"
                  />
                  <span class={styles['basicInformation-unit']}>米</span>
                </ElSpace>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem prop="postHeightType" label="杆高分类">
                <ElSelect
                  v-model={optionsValidateForm.postHeightType}
                  filterable
                  clearable
                  placeholder="请输入或选择"
                >
                  {assetWorkAreaState.postHeightTypeOpt?.value?.map((item: accomplishEnum) => (
                    <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
                  )) || []}
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem prop="lampRamLength" label="臂长">
                <ElSpace class={styles['info-form-item-full-space']} size={0}>
                  <ElInputNumber
                    v-model={optionsValidateForm.lampRamLength}
                    precision={1}
                    step={0.1}
                    min={0}
                    max={100}
                    controls={false}
                    placeholder="请输入"
                  />
                  <span class={styles['basicInformation-unit']}>米</span>
                </ElSpace>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem prop="thickness" label="灯杆壁厚">
                <ElSpace class={styles['info-form-item-full-space']} size={0}>
                  <ElInputNumber
                    v-model={optionsValidateForm.thickness}
                    precision={1}
                    step={0.1}
                    min={0}
                    max={100}
                    controls={false}
                    placeholder="请输入"
                  />
                  <span class={styles['basicInformation-unit']}>厘米</span>
                </ElSpace>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="supply"
                label="供货公司"
                rules={[{ min: 3, whitespace: true, message: '供货公司，若输入则应为3～20个字符' }]}
              >
                <ElInput
                  v-model={optionsValidateForm.supply}
                  {...{ minlength: 3, maxlength: 20 }}
                  clearable
                  placeholder="请输入"
                  onChange={handleInputChange}
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem prop="workAreaName" label="所属区域">
                <ElSelect
                  v-model={optionsValidateForm.workAreaName}
                  filterable
                  clearable
                  placeholder="请输入或选择"
                >
                  {assetWorkAreaState.workAreaSelectList?.value?.map((item: LampPostSelectEnum) => (
                    <ElOption key={item?.id} label={item?.name} value={item?.name!} />
                  )) || []}
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem prop="streetId" label="所属街道">
                <ElSelect
                  v-model={optionsValidateForm.streetId}
                  filterable
                  clearable
                  placeholder="请输入或选择"
                  onChange={streetChange}
                >
                  {streetManagementState.streetSelectList?.value?.map(
                    (item: LampPostSelectEnum) => (
                      <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                    )
                  ) || []}
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol>
              <ElFormItem prop="memo" label="备注">
                <InputTextarea
                  v-model:inputTextareaValue={optionsValidateForm.memo}
                  placeholderName="请输入"
                  limitLength={100}
                />
              </ElFormItem>
            </ElCol>
            <ElCol>
              <ElFormItem label="图片" prop="imageUrl">
                <BaseUpload
                  listType="picture-card"
                  fileList={(optionsValidateForm.imageUrl as string[])?.map?.((item) => ({
                    name: '图片',
                    url: item,
                    response: {
                      data: {
                        link: item
                      }
                    }
                  }))}
                  accept=".jpg,.png"
                  limit={12}
                  onSuccess={handleUploadSuccess}
                  onRemove={handleRemoveUploadFile}
                  v-slots={{
                    tip: () => (
                      <section>
                        <ElLink type="info" underline={false} icon={<WarningFilled />}>
                          &nbsp;支持最多上传12张图片
                        </ElLink>
                      </section>
                    )
                  }}
                >
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  点击上传
                </BaseUpload>
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      )
    }
  }
})
